package com.woniu.woniu_bx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniu.woniu_bx.mapper.DiscussMapper;
import com.woniu.woniu_bx.mapper.MomentImgMapper;
import com.woniu.woniu_bx.mapper.MomentMapper;
import com.woniu.woniu_bx.mapper.UserMapper;
import com.woniu.woniu_bx.pojo.Moment;
import com.woniu.woniu_bx.pojo.PageBean;
import com.woniu.woniu_bx.pojo.User;
import com.woniu.woniu_bx.service.MomentService;
import com.woniu.woniu_bx.utils.DateUtil;
import com.woniu.woniu_bx.vo.MomentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @ClassName MomentServiceImpl
 * @Description TODO
 * @Author 于文龙
 * @Date 2022/8/27 16:21
 * @Version 1.0
 **/
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class MomentServiceImpl extends ServiceImpl<MomentMapper, Moment> implements MomentService {

    @Autowired
    private MomentMapper momentMapper;

    @Autowired
    private MomentImgMapper momentImgMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DiscussMapper discussMapper;

    /**
     * @return void
     * @Description 动态新增
     * @Date 10:35 2022/9/1
     * @Author 魏才林
     * @Param [moment]
     **/
    @Override
    public void add(Moment moment) {
        //（1）初始化点赞数、阅读量、发布时间
        moment.setLikeNum(0);
        moment.setReadNum(0);
        SimpleDateFormat dateTimeformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        moment.setTime(dateTimeformat.format(System.currentTimeMillis()));

        //（2）将动态新增,然后通过数据库带回来的id，来实现图片的增加
        momentMapper.insert(moment);

        //（3）判断该动态是否有附带的图片
        if (moment.getImgs() != null && moment.getImgs().size() > 0) {
            momentImgMapper.insert(moment.getImgs(), moment.getId());
        }
    }

    /**
     * @return com.woniu.woniu_bx.pojo.PageBean<com.woniu.woniu_bx.pojo.Moment>
     * @Description 获得所有动态（分页）
     * @Date 11:03 2022/9/1
     * @Author 魏才林
     * @Param [pageNum, pageSize]
     **/
    @Override
//    @Cacheable(value = "momentPageBean", key = "loginUserId")
    public PageBean<Moment> getAllMoment(Integer pageNum, Integer pageSize, Integer loginUserId) {

        Page page = PageHelper.startPage(pageNum, pageSize);

        // 获取所有动态，按时间倒序
        QueryWrapper<Moment> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("time");
        List<Moment> allMoments = momentMapper.selectList(queryWrapper);

        //循环给所有动态，去查询出各自的所需的其他信息，如动态图片
        allMoments.forEach(m -> {
            m.setImgs(momentImgMapper.getAllImgByMomentId(m.getId()));
            m.setDiscussNum(discussMapper.getDiscussNumByMomentId(m.getId()));
            // 查询出发布者
            User user = userMapper.selectById(m.getUserId());
            try {
                user.setAge(DateUtil.getAge(user.getBirthday(), "yyyy-MM-dd"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            m.setUser(user);
            // 计算逻辑时间
            try {
                m.setLogicTime(DateUtil.getLogicTime(m.getTime(), "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            // 当前登录用户是否已关注动态作者
            m.setCareMomentUser(momentMapper.cares(loginUserId, m.getUserId()) != 0);
            // 当前登录用户是否已点赞
            m.setLikeMoment(momentMapper.likes(loginUserId, m.getId()) != 0);
        });

        PageBean<Moment> momentPageBean = new PageBean<>();
        momentPageBean.setPageSize(pageSize);
        momentPageBean.setData(allMoments);
        momentPageBean.setCurrPage(pageNum);
        momentPageBean.setCurrPageSize(allMoments.size());
        momentPageBean.setTotalPages(page.getPages());
        momentPageBean.setTotalNums((int) page.getTotal());

        return momentPageBean;
    }

    @Override
    public List<User> findByMyLikeId(int id) {
        return momentMapper.findByMyLikeId(id);
    }

    @Override
    public Moment details(int id) {
        Moment details = momentMapper.details(id);
        try {
            details.setLogicTime(DateUtil.getLogicTime(details.getTime(), "yyyy-MM-dd HH:mm:ss"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        details.setImgs(momentImgMapper.getAllImgByMomentId(id));

        return details;
    }

    @Override
    public void giveLike(Integer userId, Integer momentId) {
        momentMapper.giveLike(userId, momentId);
        momentMapper.updateLikeNum(momentMapper.selectById(momentId).getLikeNum() + 1, momentId);
    }

    @Override
    public void cancelLike(Integer userId, Integer momentId) {
        momentMapper.cancelLike(userId, momentId);
        momentMapper.updateLikeNum(momentMapper.selectById(momentId).getLikeNum() - 1, momentId);
    }

    /**
     * 根据用户id查询动态
     *
     * @param userId
     * @return
     */
    @Override
    public MomentVo getByUserId(Integer userId, Integer myId) {
        MomentVo momentVo = new MomentVo();
        List<Moment> moments = momentMapper.findByUserId(userId);
        moments.forEach(m -> {
            m.setImgs(momentImgMapper.getAllImgByMomentId(m.getId()));
            m.setDiscussNum(discussMapper.getDiscussNumByMomentId(m.getId()));
            // 计算逻辑时间
            try {
                m.setLogicTime(DateUtil.getLogicTime(m.getTime(), "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            // 当前登录用户是否已点赞
            m.setLikeMoment(momentMapper.likes(myId, m.getId()) != 0);
        });
        User user = userMapper.selectById(userId);
        momentVo.setMoments(moments);
        momentVo.setUser(user);
        return momentVo;
    }

    @Override
    public void deleteById(Integer id) {
        // 删除动态
        momentMapper.deleteById(id);
        // 删除图片
        momentMapper.deleteImagesByMomentId(id);
        // 删除点赞
        momentMapper.deleteDiscussByMomentId(id);
        // 删除评论
        momentMapper.deleteLikesByMomentId(id);
    }
}
